package com.pactera.jep.service.sys.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.autoconfigure.web.controller.BaseRestController;
import com.pactera.jep.core.context.Context;
import com.pactera.jep.entity.Treeable;
import com.pactera.jep.service.sys.model.UserProfile;
import com.pactera.jep.sys.dto.MetaRegionTableDto;
import com.pactera.jep.sys.model.MetaQuery;
import com.pactera.jep.sys.model.MetaRegionTable;
import com.pactera.jep.sys.model.MetaTable;
import com.pactera.jep.sys.query.constant.QueryOptions;
import com.pactera.jep.sys.query.constant.QueryRelationType;
import com.pactera.jep.sys.query.dto.QueryDto;
import com.pactera.jep.sys.query.utils.JdbcUtil;
import com.pactera.jep.sys.service.*;
import com.pactera.jep.sys.util.SQLRegexUtil;
import com.pactera.jep.web.code.WebCode;
import com.pactera.jep.web.entity.TreeNode;
import com.pactera.jep.web.util.TreeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(value = "查询分析器")
@RestController
@RequestMapping("/dataAnalysis")
public class DataAnalysisRestController extends BaseRestController<MetaQuery> {
	protected static Logger	logger	= LoggerFactory.getLogger(DataAnalysisRestController.class);
	@Autowired
	private MetaQueryService metaQueryService;
	
	@Autowired
	private MetaRelationService metaRelationService;
	
	@Autowired
	private MetaTableService metaTableService;
	
	@Autowired
	private MetaRegionTableService metaRegionTableService;
	
	@Autowired
	private MetaRegionService metaRegionService;
	
	/**
	 * 获取列表页面
	 * @return 列表页面
	 */
	@RequestMapping(value = "/main")
	public String list(Model model) {
		return "sys/dataAnalysisMain";
	}
	
	/**
	 * 点击metaTable打开tab页，跳转到画面
	 * @param tableId
	 */
/*	@RequestMapping(value = "/dataQuery")
	public String queryTableData(Model model, String id, String type, String masterTableId, String joinTableId, String data, String relationType, String masterColumnCode, String joinColumnCode){
		
		model.addAttribute("id", id);
		model.addAttribute("type", type);
		model.addAttribute("masterTableId", masterTableId);
		model.addAttribute("joinTableId", joinTableId);
		model.addAttribute("data", data);
		model.addAttribute("relationType", relationType);
		model.addAttribute("masterColumnCode", masterColumnCode);
		model.addAttribute("joinColumnCode", joinColumnCode);
		
		*//*默认为行模式*//*
		String modelView = "L";
		if(!StringUtils.isEmpty(relationType) && QueryRelationType.valueOf(relationType) == QueryRelationType.JOIN){
			modelView = "C";
		}
		model.addAttribute("modelView", modelView);
		
		*//*获取用户信息*//*
		UserProfile curUser = UserProfileUtils.getUserProfile();
		model.addAttribute("curUser", curUser);
		
		return "sys/dataAnalysisQuery";
	}*/

	/***
	 * 查询数据分析器 tree
	 * @param id 
	 * @return
	 */
	@ApiOperation(value = "查询数据分析器 tree")
	@GetMapping(value = "/queryTableTree")
	@ResponseBody
	public List<TreeNode> queryTableTree(String id) {
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		List<Treeable> treeables;
		try {
			/*获取用户信息*/
			String staffCode = Context.getIdentityContext().getIdentity().getId();
			treeables = metaQueryService.getMetaRegionsByRegionId(id, staffCode);
			String[] columns = new String[]{"type", "title", "regionCode"};
 			nodes = TreeUtils.parse(treeables, columns);

		} catch (Exception e) {
			e.printStackTrace();
		}
		for (TreeNode node :
				nodes) {
			logger.info(JSONObject.toJSON(node).toString());
		}
		return nodes;
	}
	
	/***
	 * 查询当前登录人员能访问的metaRegion
	 * @param id 
	 * @return
	 */
	@RequestMapping(value = "/queryMetaregionTree")
	@ResponseBody
	public List<TreeNode> queryMetaregionTree(String id) {
		List<TreeNode> nodes = new ArrayList<TreeNode>();
		List<Treeable> treeables;
		try {
			/*获取用户信息*/
			//UserProfile curUser = UserProfileUtils.getUserProfile();
			String staffCode = Context.getIdentityContext().getIdentity().getId();
			treeables = metaQueryService.canAccessMetaRegionByRegionId(id, staffCode);
			String[] columns = new String[]{"type", "title", "regionCode"};
 			nodes = TreeUtils.parse(treeables, columns);
		} catch (Exception e) {
			e.printStackTrace();
		}	
		return nodes;
	}
	
	/**
	 * 设置界面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/set")
	public String setTableData(String script, Model model) {
		model.addAttribute("script", script);
		return "sys/dataAnalysisSet";
	}
	
	/**
	 * 查看Sql画面跳转
	 * @return
	 */
	@ApiOperation(value = "查看Sql")
	@GetMapping(value = "/viewSql")
	@ResponseBody
	public Map<String,Object> viewSql(String querySql){
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			
			String sql = URLDecoder.decode(querySql, "UTF-8");
			
			map.put("sql", SQLRegexUtil.replace(sql));
		} catch (UnsupportedEncodingException e) { 
		}
		return map;
	}
	
	/**
	 * 保存界面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/queryName")
	public String meatQuerySave(Model model){ 
		 
		return "sys/metaQueryName";
	} 
	
	/**
	 * 查询一个关联表
	 * @param model
	 * @param tableId
	 * @return
	 */
	@RequestMapping(value = "/selectChild/{regionTableId}")
	@ResponseBody
	public Map<String, Object> getChild(Model model, @PathVariable String regionTableId){ 
		Map<String, Object> map = new HashMap<String, Object>();
		
		/*获取regionTable对象*/
		MetaRegionTable regionTable = metaRegionTableService.get(regionTableId);
		
		/*获取关联表*/
		List<MetaRegionTableDto> metaTables = metaRelationService.selectAnalysisJoinTable(regionTable.getTableId());
 
		map.put(WebCode.SUCCESS, true);
		map.put("result", metaTables);
		
		return map;
	} 
	
	/**
	 * 另存为视图
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/saveView")
	public String saveView(Model model){ 
		
		/*获取当前模式*/
		model.addAttribute("schema", JdbcUtil.getCurrentSchema());
		return "sys/dataAnalysisSaveView";
	}
	
	
	/**
	 * 验证视图名字是否已存在
	 * @param
	 * @param metaTable
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "验证视图名字是否已存在")
	@PostMapping(value = "/checkViewName")
	public Map<String, Object> checkViewName(@RequestBody String params,  MetaTable metaTable){
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject jsonObject = JSONObject.parseObject(params);
		metaTable.setSchema(jsonObject.getString("schema"));
		metaTable.setTableCode(jsonObject.getString("tableCode"));
		List<MetaTable> metatables = metaTableService.selectTables(metaTable.getSchema(), metaTable.getTableCode());
		map.put(WebCode.SUCCESS, true);
		map.put("tableExists", CollectionUtils.isNotEmpty(metatables));
		return map;
	}
	
	/**
	 * IE浏览器查看列模式，全部列
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/columnView")
	public String columnView(Model model){ 
		
		return "sys/dataAnalysisQueryColumn";
	}
	
//	/**
//	 * 获取关联表父级节点
//	 * @param relativeTableId
//	 * @param request
//	 * @return
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/getParents", method = RequestMethod.POST)
//	@ResponseBody
//	public Map<String, Object> queryChild(String relativeTableId, HttpServletRequest request) throws Exception {
//		Map<String, Object> map = new HashMap<String, Object>();
//
//		
//		/*获取关联表 regionTable对象*/
//		MetaRegionTable relativeRegionTable = metaRegionTableManager.getMetaRegionTable(relativeTableId);
//		 
//		/*获取当前表上面所有的父节点*/
//		String parents = metaRegionManager.getParents(relativeRegionTable.getRegionId());
//		
//		map.put(MessageConstant.SUCCESS, true); 
//		map.put("joinTrees", parents);
//		return map;
//	}
//	
//	
	/**
	 * 查询导出
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/queryExport")
	public void export(HttpServletRequest request, HttpServletResponse response, String tableId, String script){ 
		response.setContentType("text/html;charset=utf-8");  
		response.setContentType("application/x-msdownload;");  
		BufferedOutputStream bos = null; 
		try {
			
			/*获取关联表 regionTable对象*/
			MetaRegionTable relativeRegionTable = metaRegionTableService.get(tableId);
			
			/*初始化查询对象*/
			QueryDto queryDto = new QueryDto();
			queryDto.setScript(script);
			//UserProfile curUser = UserProfileUtils.getUserProfile();
			String staffCode = Context.getIdentityContext().getIdentity().getId();
			/*查询导出的数据*/
			byte[] outBody = metaQueryService.toXlsData(queryDto, QueryOptions.BUILD_OPTION_PRIVILEGE_REQUIRED, staffCode);
			
			/*查询tableCode*/
			MetaTable metaTable = metaTableService.get(relativeRegionTable.getTableId());
			String fileName = metaTable.getTableCode() + ".xlsx";
			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
			
			response.setHeader("Content-Length", String.valueOf(outBody.length));
			bos = new BufferedOutputStream(response.getOutputStream());
			bos.write(outBody, 0, outBody.length);
		} catch (IOException e) {
			logger.error("下载失败：" + e.getMessage());
		} finally {  
			try {
				if (bos != null)  
					bos.close();  
			} catch (IOException e) {
				logger.error("关闭IO流缓冲失败：" + e.getMessage());
			}  
        }
	}
}
